import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'
// 一级路由
// import Login from '@/views/Login'
// import Register from '@/views/Register'
// import Detail from '@/views/Detail'
import Layout from '@/views/Layout'
// 二级路由
// import Like from '@/views/Like'
// import Article from '@/views/Article'
// import Collect from '@/views/Collect'
// import User from '@/views/User'

const Detail = () => import('@/views/Detail.vue')
const Register = () => import('@/views/Register.vue')
const Login = () => import('@/views/Login.vue')
const Article = () => import('@/views/Article.vue')
const Collect = () => import('@/views/Collect.vue')
const Like = () => import('@/views/Like.vue')
const User = () => import('@/views/User.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/article',
    children: [
      { path: 'article', component: Article },
      { path: 'collect', component: Collect },
      { path: 'like', component: Like },
      { path: 'user', component: User }
    ]
  },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/detail/:id', component: Detail }
]

const router = new VueRouter({
  routes
})

// 1. 配置路由全局前置守卫
/**
 * to: 往哪里去， 到哪去的路由信息对象
 * from: 从哪来， 从哪来的路由信息对象
 * next: 放行函数
 */
router.beforeEach((to, from, next) => {
  // 1.1 白名单
  const whiteList = ['/login', '/register']
  // 1.2 获取token
  const token = getToken()
  // 1.3 判断是否有token
  if (token) {
    // 1.3.1 判断是否去登录页
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // 1.4 判断去的页面路径是否在白名单中
    if (whiteList.includes(to.path)) {
      next() // 放行
    } else {
      next('/login') // 拦截去登录页
    }
  }
})

// 2. 配置路由全局后置守卫
router.afterEach((to, from) => {
  console.log('afterEach')
})

export default router
